import 'package:date_format/date_format.dart';
import 'package:palmf_hid/common/store/user.dart';
import 'package:palmf_hid/common/utils/utils.dart';
import 'package:palmf_hid/common/values/conf.dart';
import 'package:gbk_codec/gbk_codec.dart';
import 'package:hex/hex.dart';

import 'common_order_util.dart';

///生成打印机数据
List<int> genPrintData(List<Map<String, List<int>>> data) {
  List<int> temp = [];
//头  (13字节空格 )报告单 (6字节) 3字节(忽略) 32个(-)  3字节(忽略) 10字节样本编号(样本编号文本+4字节编号)

  ///一整行线段
  List<int> allLine = [
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45,
    45
  ];

  //报告单
  List<int> report = [177, 168, 184, 230, 181, 165];

  ///打印1行
  List<int> oneLine = [27, 100, 1];
  var blackSpace = 32;
  //”:“ASCII
  List<int> colon = [163, 186];
  //”项目“ASCII
  List<int> projectInt = [207, 238, 196, 191];
  //”正常值范围：“ASCII
  List<int> rangeOfNormalValues = [
    213,
    253,
    179,
    163,
    214,
    181,
    183,
    182,
    206,
    167,
    163,
    186
  ];
//"检测结果:"ASCII
  List<int> testResult = [188, 236, 178, 226, 189, 225, 185, 251, 163, 186];
  //空格 ASCII
  List<int> black = [20];

  for (int i = 0; i < data.length; i++) {
    if (null != data[i]["hospital"]) {
      if (data[i]["hospital"]!.length > 32) {
        temp.addAll(data[i]["hospital"]!.sublist(0, 32));
      } else {
        List<int> blackSpaces = [];
        int len = (32 - data[i]["hospital"]!.length) ~/ 2;
        for (int i = 0; i < len; i++) {
          blackSpaces.add(blackSpace);
        }
        temp.addAll(blackSpaces);
        temp.addAll(data[i]["hospital"]!);
      }
    }
    temp.addAll(oneLine);
    List<int> reportList = [];
    reportList.addAll(data[i]["projectName"]!);
    reportList.addAll(report);

    if (reportList.length > 32) {
      temp.addAll(reportList.sublist(0, 32));
    } else {
      List<int> blackSpaces = [];
      int len = (32 - reportList.length) ~/ 2;
      for (int i = 0; i < len; i++) {
        blackSpaces.add(blackSpace);
      }
      temp.addAll(blackSpaces);
      temp.addAll(reportList);
    }
    temp.addAll(oneLine);
    //样本编号
    temp.addAll(data[i]["serialNo"]!);
    if (data[i]["patientName"] != null) {
      temp.addAll(oneLine);
      temp.addAll(data[i]["patientName"]!);
    }

    if (data[i]["patientAge"] != null) {
      temp.addAll(oneLine);
      temp.addAll(data[i]["patientAge"]!);
    }
    List<int> blackSpaces = [];
    for (int i = 0; i < 8; i++) {
      blackSpaces.add(blackSpace);
    }
    temp.addAll(blackSpaces);
    if (data[i]["patientSex"] != null) {
      temp.addAll(oneLine);
      temp.addAll(data[i]["patientSex"]!);
    }
    if (data[i]["time"] != null) {
      temp.addAll(oneLine);
      temp.addAll(data[i]["time"]!);
    }

    temp.addAll(oneLine);
    temp.addAll(allLine);
    temp.addAll(oneLine);

    //项目文本
    temp.addAll(projectInt);
    if (data.isNotEmpty) {
      temp.addAll([i + 1]);
    }
    temp.addAll(colon);
    temp.addAll(data[i]["projectName"]!);
    temp.addAll(oneLine);
    temp.addAll(testResult);

    if (data[i].containsKey("isResultPre") &&
        data[i]["isResultPre"]!.isNotEmpty) {
      temp.addAll(data[i]["resultDisplay"]!);
    }
    temp.addAll(data[i]["result"]!);
    if (data[i].containsKey("isResultPre") && data[i]["isResultPre"]!.isEmpty) {
      temp.addAll(data[i]["resultDisplay"]!);
    }
    temp.addAll(black);
    temp.addAll(data[i]["resultUnit"]!);
    temp.addAll(oneLine);
    temp.addAll(rangeOfNormalValues);
    temp.addAll(data[i]["range"]!);
    temp.addAll(oneLine);
    temp.addAll(allLine);
    temp.addAll(oneLine);

    temp.addAll(data[i]["checkDoc"]!);
    temp.addAll(oneLine);
    temp.addAll(data[i]["auditor"]!);
    temp.addAll(oneLine);
    temp.addAll(allLine);
    temp.addAll(oneLine);

    temp.addAll(data[i]["statement"]!);
    temp.addAll(oneLine);
    temp.addAll(data[i]["printTime"]!);
    temp.addAll(oneLine);
  }

  ///打印3行
  List<int> end = [27, 100, 3];
  temp.addAll(end);
  return temp;
}

///测试结果记录转成List<int>
Map<String, List<int>> genData(Map<String, dynamic> entity) {
  MyLogUtil().i(entity);
  Map<String, List<int>> map = {};
  List<int> checkTimeGbkCodes = gbk.encode("检测编号:");
  String checkTime = '';
  for (var i in checkTimeGbkCodes) {
    checkTime += '${i.toRadixString(16)} ';
  }
  String serialNo = entity['serialNo']!.toString();
  map["serialNo"] = HEX.decode(checkTime + asciiToHex(serialNo));
  String projectName = entity['projectName'] ?? "";
  if (projectName.contains(BT_STR)) {
    map["projectName"] = HEX.decode(
        asciiToHex(projectName.replaceAll(BT_STR, TEMP_CHAR_BT_CN))
            .replaceAll(TEMP_CHAR_BT, BT));
  } else if (projectName.contains(REF_STR)) {
    map["projectName"] = HEX.decode(
        asciiToHex(projectName.replaceAll(REF_STR, TEMP_CHAR_REF_CN))
            .replaceAll(TEMP_CHAR_REF, REF));
  } else {
    map["projectName"] = HEX.decode(asciiToHex(projectName));
  }
  if (entity['patientName'] != null) {
    MyLogUtil().i(entity['patientName']);
    List<int> gbkCodes = gbk.encode("姓名：${entity['patientName']}");
    String hex = '';
    for (var i in gbkCodes) {
      hex += '${i.toRadixString(16)} ';
    }
    map["patientName"] = HEX.decode(hex);
  }
  if (entity['patientAge'] != null) {
    MyLogUtil().i(entity['patientAge']);
    List<int> gbkCodes = gbk.encode("年龄：${entity['patientAge']}");
    String hex = '';
    for (var i in gbkCodes) {
      hex += '${i.toRadixString(16)} ';
    }
    map["patientAge"] = HEX.decode(hex);
  }
  if (entity['patientSex'] != null) {
    MyLogUtil().i(entity['patientSex']);
    List<int> gbkCodes = gbk.encode("性别：${entity['patientSex']}");
    String hex = '';
    for (var i in gbkCodes) {
      hex += '${i.toRadixString(16)} ';
    }
    map["patientSex"] = HEX.decode(hex);
  }

  if (entity['time'] != null) {
    MyLogUtil().i(entity['time']);

    String time = entity['time'].toString();

    if (time.contains(".")) {
      time = time.split(".")[0];
    }
    List<int> gbkCodes = gbk.encode("检测时间：$time");
    String hex = '';
    for (var i in gbkCodes) {
      hex += '${i.toRadixString(16)} ';
    }
    map["time"] = HEX.decode(hex);
  }

  // if ((UserStore.to.profile.org ?? " ") != "") {
  //   List<int> hospitalBbkCodes = gbk.encode(UserStore.to.profile.org ?? " ");
  //   String hospital = '';
  //   for (var i in hospitalBbkCodes) {
  //     hospital += '${i.toRadixString(16)} ';
  //   }
  //   map["hospital"] = HEX.decode(hospital);
  //   MyLogUtil().i(UserStore.to.profile.org ?? " ");
  //   MyLogUtil().i(hospital.length);
  // }

  if (entity['result'] == -9999) {
    map["result"] = HEX.decode(asciiToHex("*** ***"));
  } else {
    String referUpper = '${entity['referUpper'] ?? ""}';
    String referLower = '${entity['referLower'] ?? ''}';
    double resultD = entity['result'] ?? "0";
    if (resultD < 0) {
      resultD = 0;
    }
    String upper = entity['upper'] ?? "";
    String lower = entity['lower'] ?? "";
    String result = "";
    if (upper != "" && lower != "") {
      double upperD = double.parse(upper);
      double lowerD = double.parse(lower);
      if (resultD > upperD) {
        result = ">$upperD";
      } else if (resultD < lowerD) {
        result = "<$lowerD";
      } else if (resultD > lowerD && resultD < upperD) {
        if (referUpper != "" && resultD > double.parse(referUpper)) {
          result =
              "${resultD.toStringAsFixed((entity['saveNum'] ?? 2).toInt())}↑";
        } else if (referLower != "" && resultD < double.parse(referLower)) {
          result =
              "${resultD.toStringAsFixed((entity['saveNum'] ?? 2.toInt()))}↓";
        } else {
          result = resultD.toStringAsFixed((entity['saveNum'] ?? 2).toInt());
        }
      } else {
        result = resultD.toStringAsFixed((entity['saveNum'] ?? 2).toInt());
      }
    } else {
      result = resultD.toStringAsFixed((entity['saveNum'] ?? 2).toInt());
    }
    List<int> resultGbkCodes = gbk.encode(result);
    String resultStr = '';
    for (var i in resultGbkCodes) {
      resultStr += '${i.toRadixString(16)} ';
    }
    map["result"] = HEX.decode(resultStr);
  }
  double referUpper = double.parse(
      entity['referUpper'] == "" || entity['referUpper'] == "9999999"
          ? "-99999"
          : entity['referUpper']);
  double referLower = double.parse(
      entity['referLower'] == "" || entity['referLower'] == "9999999"
          ? "-99999"
          : entity['referLower']);
  List<int> resultUnitGbkCodes = gbk.encode("${entity['resultUnit']}");
  String resultUnitStr = '';
  for (var i in resultUnitGbkCodes) {
    resultUnitStr += '${i.toRadixString(16)} ';
  }
  map["resultUnit"] = HEX.decode(resultUnitStr);

  if (referUpper == -99999 && referLower == -99999) {
    map["range"] = HEX.decode(asciiToHex(' -- '));
  } else {
    if (referUpper == -99999 && referLower != -99999) {
      map["range"] = HEX.decode(asciiToHex(
          '> ${referLower.toStringAsFixed(entity['saveNum'] ?? 2)} '));
    } else if (referUpper != -99999 && referLower == -99999) {
      map["range"] = HEX.decode(asciiToHex(
          '< ${referUpper.toStringAsFixed(entity['saveNum'] ?? 2)} '));
    } else {
      map["range"] = HEX.decode(asciiToHex(
          ' ${referLower.toStringAsFixed(entity['saveNum'] ?? 2)} -- ${referUpper.toStringAsFixed(entity['saveNum'] ?? 2)} '));
    }
  }

  List<int> checkDocGbkCodes = gbk.encode("检验医生:");
  String checkDoc = '';
  for (var i in checkDocGbkCodes) {
    checkDoc += '${i.toRadixString(16)} ';
  }
  map["checkDoc"] = HEX.decode(checkDoc);

  List<int> auditorGbkCodes = gbk.encode("审核者:");
  String auditor = '';
  for (var i in auditorGbkCodes) {
    auditor += '${i.toRadixString(16)} ';
  }
  map["auditor"] = HEX.decode(auditor);

  List<int> statementGbkCodes = gbk.encode("实验声明:本结果仅对本份标本负责!");
  String statement = '';
  for (var i in statementGbkCodes) {
    statement += '${i.toRadixString(16)} ';
  }
  map["statement"] = HEX.decode(statement);

  List<int> printTimeGbkCodes = gbk.encode('打印时间:${formatDate(DateTime.now(), [
        yyyy,
        '-',
        mm,
        '-',
        dd,
        " ",
        HH,
        ':',
        nn,
        ':',
        ss
      ])}');
  String printTime = '';
  for (var i in printTimeGbkCodes) {
    printTime += '${i.toRadixString(16)} ';
  }

  map["printTime"] = HEX.decode(printTime);
  // MyLogUtil().i(map);
  return map;
}
